<template>
  <div>
    <div class="analysisGeneration-content1">
      <el-form :model="propsData" ref="analysisGeneration-content1" class="analysisGeneration-content1-form">
        <el-form-item label="一层文件夹" prop="folder1" class="s" :rules="[{ required: true, message: '请输入一层文件夹', trigger: 'blur' }]">
          <el-input placeholder="一层文件夹" v-model="propsData.folder1" clearable/>
        </el-form-item>
        <el-form-item label="两层文件夹" prop="folder1" class="s" :rules="[{ required: true, message: '请输入两层文件夹', trigger: 'blur' }]">
          <el-input placeholder="两层文件夹" v-model="propsData.folder2" clearable/>
        </el-form-item>
        <el-form-item label="Title名字" prop="addEditTitle" class="s" :rules="[{ required: true, message: '请输入新增修改Title', trigger: 'blur' }]">
          <el-input placeholder="新增修改Title" v-model="propsData.addEditTitle" clearable/>
        </el-form-item>
        <el-form-item label="时间搜索名称" prop="addEditTitle" class="s" :rules="[]">
          <el-input placeholder="时间搜索名称" v-model="propsData.timeSearch" clearable/>
        </el-form-item>
      </el-form>
    </div>

    <div class="analysisGeneration-content2">
      <span class="s">table数据解析</span>
      <el-input v-model="propsData.tableDataParsing" placeholder="请输入解析数据" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" clearable class="mr-12 "></el-input>
      <el-button type="primary" @click="startParsingClick">表格数据解析</el-button>
    </div>
    <div class="analysisGeneration-content3">
      <el-button type="success" size="medium" @click="generatePageCodeClick">生成页面代码</el-button>
      <el-button type="info" size="medium" @click="temporaryStorage1">暂存当前生成数据</el-button>
      <el-button type="warning" size="medium" @click="temporaryStorage2">读取前面暂存的数据</el-button>
      <el-upload
          class="upload-demo" ref="upload"
          accept=".js"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="importBackupClick"
          :show-file-list="false"
          :auto-upload="false"
      >
        <el-button slot="trigger" type="primary" style="margin: 0 12px">导入备份生成器数据
        </el-button>
      </el-upload>
      <el-button type="danger" size="medium" @click="initializationClcik">初始化</el-button>
    </div>

    <!--表格配置-->
    <tableSet :propsData="propsData"></tableSet>

  </div>
</template>

<script>
import tableSet from "@/views/ruoyi/tableSet";
import {saveAs} from 'file-saver';

export default {
  components: {tableSet},
  props: [],
  data() {
    return {
      //导出文件集合
      exportFileData: [],
      endScript: '</scr' + 'ipt>',
      allStyle: '<style lang="scss" scoped></style>',
      propsData: {
        folder1: '',//一层文件夹
        folder2: '',//两层文件夹
        addEditTitle: '',//新增修改Dialog title 名字
        tableDataParsing: '',//表格数据解析
        timeSearch:'',//时间搜索名称
        //表格配置
        tableProp: {
          addBut: false,//增 按钮
          delBut: false,//删 按钮
          editBut: false,//改 按钮
          queryBut: false,//查 按钮
          tableArray: []
        }
      },
    };
  },
  mounted() {
  },
  methods: {
    //表格数据解析
    startParsingClick() {
      if (!this.propsData.tableDataParsing) {
        this.$message.error('请输入解析数据')
        return false
      }
      let dataParsing = this.propsData.tableDataParsing.split('\n')
      for (let i = 0; i < dataParsing.length; i++) {
        let data = dataParsing[i].trim().split(';//');
        if (data[1].includes('：')) {
          //处理多选框，单选框，下拉框 值
          let analysis1 = data[1].split('：');
          let analysis2 = analysis1[1].split('，');
          let optionJson = ''
          for (let j = 0; j < analysis2.length; j++) {
            let optionData = analysis2[j].split('-');
            optionJson += `{label:'${optionData[1]}',value:'${optionData[0]}'},
`
          }
          let jsonData = {
            id: new Date().getTime(),
            name: analysis1[0],//名称
            type: '下拉框',//数据类型
            field: data[0],//字段
            sort: '10',//排序
            searchField: false,//tabs搜索字段
            tableSee: false,//表格不显示 true是
            addSee: false,//新增不显示 true是
            editSee: false,//修改不显示 true是
            //单选框-下拉框-多选框 数据来源
            selectProp: {
              dataSources: '自定义',//单选框-下拉框-多选框 数据来源
              text: optionJson,
            },
          }
          this.propsData.tableProp.tableArray.push(jsonData);
        } else {
          let jsonData = {
            id: new Date().getTime(),
            name: data[1],//名称
            type: '输入框',//数据类型
            field: data[0],//字段
            sort: '10',//排序
            searchField: false,//tabs搜索字段
            tableSee: false,//表格不显示 true是
            addSee: false,//新增不显示 true是
            editSee: false,//修改不显示 true是
            //单选框-下拉框-多选框 数据来源
            selectProp: {
              dataSources: '自定义',//单选框-下拉框-多选框 数据来源
              text: `{label:'',value:''},`,
            }
          }
          this.propsData.tableProp.tableArray.push(jsonData);
        }
        this.propsData.tableProp.isDrawer = true;
      }
    },
    //初始化
    initializationClcik() {
      this.$confirm('此操作将刷新页面初始化?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(0);
      }).catch(() => {
        this.$message.info('已取消初始化');
      });
    },
    //暂存当前生成数据
    temporaryStorage1() {
      this.$confirm('是否暂存当前生成数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.localStorage.setItem('propsData', JSON.stringify(this.propsData));
        this.$message.success('暂存成功');
      }).catch(() => {
        this.$message.info('已取消暂存当前生成数据');
      });
    },
    //读取前面暂存的数据
    temporaryStorage2() {
      this.$confirm('是否读取前面暂存的数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let propsData = window.localStorage.getItem('propsData');
        if (propsData) {
          let propsDataCody = JSON.parse(propsData)
          this.propsData = propsDataCody;
          this.$message.success('读取成功');
        } else {
          this.$message.error('暂无暂存数据');
        }
      }).catch(() => {
        this.$message.info('已取消读取前面暂存的数据');
      });
    },
    //导入备份生成器数据
    importBackupClick(file) {
      console.log(23123)
      const reader = new FileReader()
      reader.readAsText(file.raw)
      reader.onload = (event) => {
        let propsData = event.target.result;
        let propsDataCody = JSON.parse(propsData)
        this.propsData = propsDataCody;
        this.$message.success('导入成功');
      }
    },

    //生产代码
    generatePageCodeClick() {
      this.exportFileData=[];
      if (this.propsData.tableProp.tableArray.length == 0) {
        this.$message.info('请先table数据解析');
        return false;
      }
      this.$refs['analysisGeneration-content1'].validate(valid => {
        if (valid) {
          let tableArrayAll = this.propsData.tableProp.tableArray.sort(function (p1, p2) { //如果返回负数 p1在前 如果返回正数 p2在前
            return p1.sort - p2.sort
          })

          //把数据分割好
          let queryData = [];//查询数据
          let tableData = [];//表格数据
          let addEditData = [];//新增修改数据
          let optionData = '';//下拉选项数据
          for (let i = 0; i < tableArrayAll.length; i++) {
            //查询相关操作
            if (tableArrayAll[i].searchField) {
              queryData.push(tableArrayAll[i]);
            }
            //表格数据
            if (!tableArrayAll[i].tableSee) {
              tableData.push(tableArrayAll[i]);
            }
            //新增修改数据
            if (!tableArrayAll[i].addSee || !tableArrayAll[i].editSee) {
              addEditData.push(tableArrayAll[i]);
            }
            //下拉选项数据
            if (['下拉框'].includes(tableArrayAll[i].type)) {
              if (tableArrayAll[i].selectProp.dataSources == '自定义') {
                let str = `[
                                ${tableArrayAll[i].selectProp.text}
                           ]`;
                optionData += `//${tableArrayAll[i].name} 选项
                                   ${tableArrayAll[i].field}Option:${str},
                        `
              }
            }
          }

          //搜索相关操作  开始
          let queryVue = '';//搜索vue
          let queryField = '';//搜索的字段
          if (queryData.length > 0) {
            queryVue += `<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
                        `
            for (let i = 0; i < queryData.length; i++) {
              if (['输入框'].includes(queryData[i].type)) {
                queryVue += `<el-form-item label="${queryData[i].name}" prop="accountId">
                            <el-input v-model="queryParams.${queryData[i].field}" placeholder="请输入${queryData[i].name}" clearable style="width: 240px" @keyup.enter.native="handleQuery"/>
                        </el-form-item>
              `
              }
              if (['下拉框'].includes(queryData[i].type)) {
                queryVue += `<el-form-item label="${queryData[i].name}" prop="status">
                              <el-select v-model="queryParams.${queryData[i].field}" placeholder="请选择${queryData[i].name}" clearable style="width: 240px">
                                <el-option v-for="item in optionData.${queryData[i].field}Option" :key="item.value" :label="item.label" :value="item.value"/>
                              </el-select>
                           </el-form-item>
              `
              }
              queryField += `${queryData[i].field}:'',
            `
            }
            //搜索时间
            if(this.propsData.timeSearch){
                queryVue+=`<el-form-item label="${this.propsData.timeSearch}">
                            <el-date-picker
                              v-model="dateRange"
                              style="width: 340px"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              :default-time="['00:00:00', '23:59:59']"
                              type="datetimerange"
                              range-separator="-"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                            ></el-date-picker>
                          </el-form-item>
                `
            }


            queryVue += `<el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                          </el-form-item>
                        </el-form>
                       `
          }
          //搜索相关操作  结束

          //表格头部按钮 开始
          let tableTitleBut = '';//表格头部按钮 vue
          if (this.propsData.tableProp.addBut) {
            tableTitleBut += `<el-row :gutter="10" class="mb8">
                              <el-col :span="1.5">
                                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['${this.propsData.folder1}:${this.propsData.folder2}:add']">新增</el-button>
                              </el-col>
                              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
                            </el-row>
            `
          } else {
            tableTitleBut += `<el-row :gutter="10" class="mb8">
                              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
                            </el-row>
            `
          }
          //表格头部按钮 结束

          //表格 开始
          let tableVue = '';//表格Vue
          let columns = '';//表格下拉勾选是否显示
          if (tableData.length > 0) {
            tableVue += `<el-table v-loading="setParamsData.tableLoading" :data="tableData">
                             <el-table-column label="序号" type="index" width="50" align="center" fixed="left"/>
              `
            for (let i = 0; i < tableData.length; i++) {
              if (['输入框', '文本域'].includes(tableData[i].type)) {
                tableVue += `<el-table-column label="${tableData[i].name}" key="${tableData[i].field}" prop="${tableData[i].field}" v-if="columns[${i}].visible" align="center" :show-overflow-tooltip="true"/>
                `
              }
              if (['下拉框'].includes(tableData[i].type)) {
                tableVue += `<el-table-column label="${tableData[i].name}" key="${tableData[i].field}" v-if="columns[${i}].visible" align="center" :show-overflow-tooltip="true">
                              <template slot-scope="scope">
                                <template v-for="item in optionData.${tableData[i].field}Option">
                                  <template v-if="scope.row.${tableData[i].field}==item.value">
                                    {{ item.label }}
                                  </template>
                                </template>
                              </template>
                            </el-table-column>
                `
              }
              if (['日期和时间'].includes(tableData[i].type)) {
                tableVue += `<el-table-column label="${tableData[i].name}" v-if="columns[${i}].visible" align="center" :show-overflow-tooltip="true" width="180">
                            <template slot-scope="scope">
                              <span>{{ parseTime(scope.row.${tableData[i].field}) }}</span>
                            </template>
                          </el-table-column>
              `
              }
              columns += `{ key: ${i}, label: '${tableData[i].name}', visible: true },
            `
            }
            if (this.propsData.tableProp.editBut || this.propsData.tableProp.delBut) {
              tableVue += `<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                          <template slot-scope="scope">
              `
              if (this.propsData.tableProp.editBut) {
                tableVue += `<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['${this.propsData.folder1}:${this.propsData.folder2}:edit']">修改</el-button>
                `
              }
              if (this.propsData.tableProp.delBut) {
                tableVue += `<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['${this.propsData.folder1}:${this.propsData.folder2}:remove']">删除</el-button>
              `
              }
              tableVue += ` </template>
                        </el-table-column>
            `
            }
            tableVue += `</el-table>
            `
          }
          //表格 结束


          //添加或修改dialog 开始
          let addEditVue = '';//添加或修改dialog vue
          let addEditField = '';//添加或修改的字段
          let divisionArray = [];//把数组分割出多个数组每组2个
          if (addEditData.length > 0) {
            addEditVue += `<el-dialog :title="setParamsData.dialogTitle" width="750px" :visible.sync="setParamsData.addEditOpen" append-to-body>
                            <el-form ref="formData" :model="formData" label-width="140px">
            `
            divisionArray = this.Utils.toSplit(addEditData, 2);
            for (let i = 0; i < divisionArray.length; i++) {
              addEditVue += `<el-row>
              `
              for (let j = 0; j < divisionArray[i].length; j++) {
                addEditField+=`${divisionArray[i][j].field}:'',//${divisionArray[i][j].name}
                `
                if (['输入框'].includes(divisionArray[i][j].type)) {
                  addEditVue += `<el-col :span="12">
                                  <el-form-item label="${divisionArray[i][j].name}" prop="${divisionArray[i][j].field}" :rules="[]">
                                    <el-input v-model="formData.${divisionArray[i][j].field}" placeholder="请输入${divisionArray[i][j].name}" clearable/>
                                  </el-form-item>
                                </el-col>
                  `
                }
                if (['文本域'].includes(divisionArray[i][j].type)) {
                  addEditVue += `<el-col :span="24">
                                  <el-form-item label="${divisionArray[i][j].name}" prop="${divisionArray[i][j].field}">
                                    <el-input v-model="formData.${divisionArray[i][j].field}" type="textarea" placeholder="请输入${divisionArray[i][j].name}" :autosize="{ minRows: 2, maxRows: 4}" maxlength="300" show-word-limit></el-input>
                                  </el-form-item>
                                </el-col>
                  `
                }
                if (['下拉框'].includes(divisionArray[i][j].type)) {
                  addEditVue += `<el-col :span="12">
                                    <el-form-item label="${divisionArray[i][j].name}">
                                      <el-select v-model="formData.${divisionArray[i][j].field}" placeholder="请选择${divisionArray[i][j].name}" filterable clearable>
                                        <el-option v-for="item in optionData.${divisionArray[i][j].field}Option" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                      </el-select>
                                    </el-form-item>
                                  </el-col>
                    `
                }
              }
              addEditVue += `</el-row>
              `
            }
            addEditVue+=`</el-form>
                            <div slot="footer" class="dialog-footer">
                              <el-button type="primary" @click="submitForm">确 定</el-button>
                              <el-button @click="cancel">取 消</el-button>
                            </div>
                          </el-dialog>
            `
          }
          //添加或修改dialog 结束

          let folder2 = this.Utils.englishInitialCapital(this.propsData.folder2);//二层文件夹首字母大写

          let vueData = `
           <template>
            <div class="app-container">
            <!--查询条件-->
                ${queryVue}
            <!--表格头部按钮-->
                ${tableTitleBut}
            <!--表格-->
                ${tableVue}
            <!--分页-->
                <pagination
                  v-show="queryParams.total>0"
                  :total="queryParams.total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"
                />
             <!-- 添加或修改用户配置对话框 -->
                 ${addEditVue}
             </div>
            </template>
            <script>
                import { list${folder2},add${folder2}, del${folder2}, get${folder2}, update${folder2}} from '@/api/${this.propsData.folder1}/${this.propsData.folder2}'
                export default {
                  name: '${folder2}',
                  components: {},
                  props: [],
                  data() {
                    return {
                      showSearch: true,//显示查询条件
                      //日期范围搜索
                      dateRange: [],
                      //查询参数
                      queryParams: {
                        pageNum: 1,//当前第几页
                        pageSize: 10,//一页多少条
                        total: 0,// 总条数
                        ${queryField}},
                      // 表单参数
                      formData: {
                        id: '',//自增ID
                        ${addEditField}},
                      //表格相关参数
                      tableData: [],
                      //表格相信参数左边选择是否选显示
                      columns: [
                        ${columns}],
                      //配置相关参数
                      setParamsData: {
                        dialogTitle: '',//dialog表头显示什么
                        addEditOpen: false,//新增修改dialog
                        tableLoading: false//表格loading
                      },
                      //选项参数
                      optionData: {
                        ${optionData}}
                  }
                },
                mounted() {
                  this.listAllOption();
                  this.getList();
                },
                activated() {
                  this.listAllOption();
                },
                methods: {
                      //全部接口下拉
                      listAllOption(){},
                    /** 查询列表初始化 */
                      getList() {
                        this.setParamsData.tableLoading = true
                        list${folder2}(this.addDateRange(this.queryParams,this.dateRange)).then(response => {
                            if(response.rows.length==0){
                              if(this.queryParams.pageNum!=1){
                                this.queryParams.pageNum=this.queryParams.pageNum-1;
                                this.getList();
                                 return false;
                              }
                            }
                            this.tableData = response.rows;
                            this.queryParams.total = response.total;
                            this.setParamsData.tableLoading = false;
                          }
                        )
                      },
                    /** 新增修改提交按钮 */
                      submitForm: function() {
                        this.$refs['formData'].validate(valid => {
                          if (valid) {
                            if (this.formData.id) {
                              update${folder2}(this.formData).then(response => {
                                this.$modal.msgSuccess('修改成功');
                                this.setParamsData.addEditOpen = false;
                                this.getList();
                              })
                            } else {
                              add${folder2}(this.formData).then(response => {
                                this.$modal.msgSuccess('新增成功');
                                this.setParamsData.addEditOpen = false;
                                this.getList();
                              })
                            }
                          }
                        })
                      },
                    /** 修改按钮操作 */
                      handleUpdate(row) {
                        this.formData = this.$options.data().formData;
                        const id = row.id;
                        get${folder2}(id).then(response => {
                          this.formData = response.data;
                          this.setParamsData.addEditOpen = true;
                          this.setParamsData.dialogTitle = '修改${this.propsData.addEditTitle}';
                        })
                      },
                     /** 删除按钮操作 */
                      handleDelete(row) {
                        const id = row.id;
                        this.$modal.confirm('是否确认删除数据项？').then(function() {
                          return del${folder2}(id)
                        }).then(() => {
                          this.getList();
                          this.$modal.msgSuccess('删除成功')
                        }).catch(() => {
                        })
                      },

                    /** 新增修改dialog 取消按钮 */
                      cancel() {
                        this.setParamsData.addEditOpen = false;
                        this.formData = this.$options.data().formData;
                      },
                    /** 点击新增按钮 */
                    handleAdd() {
                      this.formData = this.$options.data().formData;
                      this.setParamsData.addEditOpen = true;
                      this.setParamsData.dialogTitle = '添加${this.propsData.addEditTitle}';
                    },
                    /** 搜索按钮操作 */
                    handleQuery() {
                      this.queryParams.pageNum = 1;
                      this.getList();
                    },
                    /** 重置按钮操作 */
                    resetQuery() {
                      this.resetForm('queryForm');
                      this.handleQuery();
                    }
                  }
                }
            ${this.endScript}
            ${this.allStyle}
          `
          //生成 vue
          let jsonData = {
            name: `index.vue`,//文件名称
            data: vueData,
            status: `vue文件`,
          }
          this.exportFileData.push(jsonData);

          //api 生产
          let apiData=`import request from '@/utils/request'
                        import { parseStrEmpty } from '@/utils/ruoyi'

                        // 查询列表
                        export function list${folder2}(query) {
                          return request({
                            url: '/monitor/${this.propsData.folder2}/list',
                            method: 'get',
                            params: query
                          })
                        }

                        // 查询详细
                        export function get${folder2}(id) {
                          return request({
                            url: '/monitor/${this.propsData.folder2}/' + parseStrEmpty(id),
                            method: 'get'
                          })
                        }

                        // 新增
                        export function add${folder2}(data) {
                          return request({
                            url: '/monitor/${this.propsData.folder2}',
                            method: 'post',
                            data: data
                          })
                        }

                        // 修改
                        export function update${folder2}(data) {
                          return request({
                            url: '/monitor/${this.propsData.folder2}',
                            method: 'put',
                            data: data
                          })
                        }

                        // 删除
                        export function del${folder2}(id) {
                          return request({
                            url: '/monitor/${this.propsData.folder2}/' + id,
                            method: 'delete'
                          })
                        }
          `
          let apiJsonData = {
            name: `${this.propsData.folder2}.js`,//api文件名称
            data: apiData,//api 数据
            status: `${this.propsData.folder2}api文件`
          }
          this.exportFileData.push(apiJsonData);

          //生成备份生成器生成数据文件 开始
          let backupsData = "";
          backupsData = JSON.stringify(this.propsData);
          let backupsJsonData = {
            name: `${this.propsData.folder2}backups.js`,//api文件名称
            data: backupsData,//api 数据
            status: `${this.propsData.folder2}备份生成器生成数据文件`
          }
          this.exportFileData.push(backupsJsonData)

          //生成文件
          if (this.exportFileData.length) {
            (async () => {
              //-----------------------------------------------------
              //批量生成路由文件
              for (let i = 0; i < this.exportFileData.length; i++) {
                await this.Utils.delay(1000);
                //生成文件
                let codeStr = this.exportFileData[i].data;
                let blob = new Blob([codeStr], {type: 'text/plain;charset=utf-8'})
                saveAs(blob, this.exportFileData[i].name)
              }
            })();
          }


        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
